package com.soushangxing.comfyuibackendv2.controller

import com.soushangxing.comfyuibackendv2.bean.GlobalQueue
import com.soushangxing.comfyuibackendv2.bean.ResponseType
import com.soushangxing.comfyuibackendv2.service.ComfyUIModelService
import com.soushangxing.comfyuibackendv2.service.ComfyUIService
import com.soushangxing.comfyuibackendv2.service.UserService
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.multipart.MultipartFile
import jakarta.servlet.http.HttpServletRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.GetMapping
import java.util.UUID

@CrossOrigin
@Controller
@ResponseBody
@RequestMapping("comfy")
class ComfyUIController {

    @Autowired
    lateinit var userService:UserService
    @Autowired
    lateinit var comfyUIService:ComfyUIService
    @Autowired
    lateinit var comfyUIModelService:ComfyUIModelService

    /**
     * 通用流程【新版，由后端全局分配队列】
     */
    @PostMapping("prompt")
    suspend fun prompt(taskId:String?,
                       type:String, file: MultipartFile?,
                       positive:String?, negative:String?,
                       denoise:String?,
                       request:HttpServletRequest): ResponseType {
        val userId = userService.getIdByRequest(request)
        if (userId.isNullOrEmpty()){
            return ResponseType(null,2,"登录已过期")
        }

        var taskIdParam = taskId
        if (taskIdParam.isNullOrEmpty()){
            taskIdParam = UUID.randomUUID().toString()
        }
        return comfyUIModelService.dispatch(taskIdParam,userId,type,file,positive,negative,denoise)
    }

    /**
     * 获取流程当前进度
     */
    @GetMapping("progress")
    fun getProgress(taskId:String,
                       request:HttpServletRequest): ResponseType {
        val userId = userService.getIdByRequest(request)
        if (userId.isNullOrEmpty()){
            return ResponseType(null,2,"登录已过期")
        }
        return comfyUIService.getProgress(taskId,userId)
    }

}
